# -*- coding: utf-8 -*-
"""
@Time    : 2024/7/11 14:10 
@Author  : ZhangShenao 
@File    : generator.py 
@Desc    : 生成器Generator

生成器Generator是懒人版本的迭代器,是lazy模式的一种应用

在迭代器中,如果想要枚举全部元素,那么这些元素需要提前生成。但是生成器不需要,它的元素是动态生成的

生成器的写法:(i for i in range(100000000))
只有在调用next()函数时,才会生成下一个元素
"""
import os

import psutil


def print_memory_usage(hint):
    """打印当前程序的内存占用"""
    pid = os.getpid()
    process = psutil.Process(pid)
    memory_info = process.memory_full_info()
    print(f'[{hint}] memory usage: {memory_info.uss / 1024 / 1024} MB')


def sum_by_iterator():
    """使用迭代器求和"""
    print_memory_usage('before init iterator')
    l = [x for x in range(0, 100000000)]
    print_memory_usage('after init iterator')
    print(sum(l))
    print_memory_usage('after calc sum by iterator')


def sum_by_generator():
    """使用生成器求和"""
    print_memory_usage('before init generator')
    l = (x for x in range(0, 100000000))
    print_memory_usage('after init generator')
    print(sum(l))
    print_memory_usage('after calc sum by generator')
